package com.sh.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.util.StringUtils;
import com.sh.common.ResponseInfoEnum;
import com.sh.common.ReturnVO;
import com.sh.entity.Customer;
import com.sh.entity.Oil;
import com.sh.entity.SystemParam;
import com.sh.entity.Transport;
import com.sh.entity.User;
import com.sh.service.CustomerService;
import com.sh.service.RptService;
import com.sh.service.TransportService;
import com.sh.util.DateUtil;
import com.sh.util.ExcelUtil;
import com.sh.util.FileUitl;

import cn.hutool.core.util.NumberUtil;

/**
 *  运输 相关 controller
 * */
@RestController
@RequestMapping("/api/transport")
public class TransportController extends BaseController{


	@Autowired
	TransportService transportService;

	@Autowired
	CustomerService customerService;

	@Autowired
	RptService rptService;

	@ResponseBody
	@RequestMapping("/listTransport")
	public Object listTransport(
			@RequestParam(value = "startPage",required = false,defaultValue="1") int startPage,
			@RequestParam(value = "pageCount",required = false,defaultValue="100") int pageCount,
			@RequestParam(value = "transportStartDate",required = false) String transportStartDate,
			@RequestParam(value = "transportEndDate",required = false) String transportEndDate,
			@RequestParam(value = "customerName",required = false) String customerName,
			@RequestParam(value = "carNum",required = false) String carNum,
			@RequestParam(value = "carOnwer",required = false) String carOnwer,
			@RequestParam(value = "unloadAddr",required = false) String unloadAddr,
			@RequestParam(value = "loadAddr",required = false) String loadAddr){

		Map<String,Object> conMap = new HashMap<String,Object>();
		conMap.put("transportStartDate", transportStartDate);
		conMap.put("transportEndDate", transportEndDate);
		conMap.put("customerName", customerName);
		conMap.put("carOnwer", carOnwer);
		conMap.put("unloadAddr", unloadAddr);
		conMap.put("loadAddr", loadAddr);

		//分页 开始  //返回数量  pageCount
		int start = (startPage-1)*pageCount;


		conMap.put("start", start);
		conMap.put("pageCount", pageCount);


		List<Transport> list =
				transportService.listTransport(conMap);

		int count =
				transportService.listTransportCount(conMap);

		return succForPage(ResponseInfoEnum.TRANSPORT_QUERY_SUCCESS, list,count);

	}

	//上传 excel文件,并且到DB
	@ResponseBody
	@RequestMapping("/uploadTransport")
	public ReturnVO uploadTransport(
			MultipartFile stoneFile){

		User user = getLoginUser();

		SystemParam rootNode = null;
		try {
			if(!stoneFile.isEmpty()){
				String path = FileUitl.createFile(stoneFile,serverPath);
				List<List<Object>> list =
						ExcelUtil.readExcelFirstSheet(path);

				//验证 数据中是不是存在 结转数据
				String carryMsg = checkCarryData(list);
				if(!"".equals(carryMsg)){
					return failForService("400", ResponseInfoEnum.TRANSPORT_UPLOAD_FAILED,carryMsg);
				}

				//检验数据的准确性，并转换为  List<Transport> 格式
				Map<String,Object> map =
						checkDataAndToBO(list,"1");
				String msg = (String)map.get("msg");
				if("".equals(msg)){
					//没有错误继续执行下面步骤
					List<Transport> checkList = (List<Transport>)map.get("list");
					String sysTime = DateUtil.getSysTime("yyyy-MM-dd hh:mm:ss");
					String rntMsg =
							transportService.saveUploadTransport(checkList,user,sysTime);
				}else{
					//有错误
					return failForService("400", ResponseInfoEnum.TRANSPORT_UPLOAD_FAILED,msg);
				}


			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.error("读取文件错误:",e);
			return failForService("400", ResponseInfoEnum.TRANSPORT_UPLOAD_FAILED,e.getMessage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("上传文件错误:",e);
			return failForService("400", ResponseInfoEnum.TRANSPORT_UPLOAD_FAILED,e.getMessage());
		}
		return succForService(ResponseInfoEnum.TRANSPORT_UPLOAD_SUCCESS, null);

	}

	/**
	 * 上传的数据 验证 是不是包含 已经结转的数据
	 * */
	private String checkCarryData(List<List<Object>> list) {
		// TODO Auto-generated method stub

		//验证 需要修改的数据 是不是已经 结转
		List<String> yearList = new ArrayList<>();

		String yearTmp = "";
		for(int i=0;i<list.size();i++){
			List<Object> listTmp = list.get(i);
			yearTmp = (String)listTmp.get(0);
			if(DateUtil.checkDateFormat(yearTmp,"yyyy-MM-dd")){
				if(!yearList.contains(yearTmp)){
					yearList.add(yearTmp.split("-")[0]);
				}
			}
		}
		String checkDataCarryMsg =
				rptService.checkDataCarry(yearList);

		return checkDataCarryMsg;
	}

	//上传 批量修改的 excel文件,插入到DB
	@ResponseBody
	@RequestMapping("/uploadTransportForUpdate")
	public ReturnVO uploadTransportForUpdate(
			MultipartFile batUpdateFile){

		User user = getLoginUser();

		SystemParam rootNode = null;
		try {
			if(!batUpdateFile.isEmpty()){
				String path = FileUitl.createFile(batUpdateFile,serverPath);
				List<List<Object>> list =
						ExcelUtil.readExcelFirstSheet(path);

				//验证 数据中是不是存在 结转数据
				String carryMsg = checkCarryData(list);
				if(!"".equals(carryMsg)){
					return failForService("400", ResponseInfoEnum.TRANSPORT_UPLOAD_FAILED,carryMsg);
				}


				//检验数据的准确性，并转换为  List<Transport> 格式
				//这里 是批量修改，有可能有重复数据，所以不需要重复要争
				Map<String,Object> map =
						checkDataAndToBO(list,"0");

				String msg = (String)map.get("msg");
				if("".equals(msg)){
					//没有错误继续执行下面步骤
					List<Transport> checkList = (List<Transport>)map.get("list");
					String sysTime = DateUtil.getSysTime("yyyy-MM-dd hh:mm:ss");
					String rntMsg =
							transportService.updateUploadTransport(checkList,user,sysTime);
				}else{
					//有错误
					return failForService("400", ResponseInfoEnum.TRANSPORT_UPLOAD_FAILED,msg);
				}


			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.error("读取文件错误:",e);
			return failForService("400", ResponseInfoEnum.TRANSPORT_UPLOAD_FAILED,e.getMessage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("上传文件错误:",e);
			return failForService("400", ResponseInfoEnum.TRANSPORT_UPLOAD_FAILED,e.getMessage());
		}
		return succForService(ResponseInfoEnum.TRANSPORT_UPLOAD_SUCCESS, null);

	}



	//检验数据的准确性，并转换为  List<Stone> 格式
	private Map<String,Object> checkDataAndToBO(List<List<Object>> list,String isCheckRepeat) {
		// TODO Auto-generated method stub
		Map<String,Object> map = new HashMap<String,Object>();

		StringBuffer sb = new StringBuffer();
		sb.append("");

		List<Transport> rtnList = new ArrayList<Transport>();
		for(int i=0;i<list.size();i++){
			List<Object> listTmp = list.get(i);
			Transport obj = new Transport();
			//日期
			obj.setTransportDate((String)listTmp.get(0));

			//客户
			obj.setCustomerName((String)listTmp.get(1));
			//装货地
			obj.setLoadAddr((String)listTmp.get(2));
			//卸货地
			obj.setUnloadAddr((String)listTmp.get(3));
			//代车号
			obj.setReplaceCarNum((String)listTmp.get(4));
			//车号
			obj.setCarNum((String)listTmp.get(5));
			//货物名称
			obj.setGoodsName((String)listTmp.get(6));
			//重量
			obj.setWeight((String)listTmp.get(7));
			//单价
			obj.setUnitPrice((String)listTmp.get(8));
			//金额
			obj.setAmount((String)listTmp.get(9));
			//客户单价
			obj.setCustomerUnitPrice((String)listTmp.get(10));
			//应收金额
			obj.setReceiveAmount((String)listTmp.get(11));

			//包车费用
			obj.setCharterPrice((String)listTmp.get(12));

			//其他费用
			obj.setOtherPrice((String)listTmp.get(13));
			//回扣
			obj.setRebates((String)listTmp.get(14));
			//结算方式
			obj.setSettlement((String)listTmp.get(15));
			//备注
			obj.setRemark((String)listTmp.get(16));
			//车主
			obj.setCarOwner((String)listTmp.get(17));

			String msg = checkData(obj,isCheckRepeat);
			if(!"".equals(msg)){
				sb.append("第 "+(i+1)+"行数据："+msg + "\n");
			}


			rtnList.add(obj);
		}
		map.put("msg", sb.toString());
		map.put("list", rtnList);
		return map;
	}

	/**
	 * 批量 删除 运输信息
	 * 删除之前需要 进行 数据验证是不是 当年数据，如果是当前数据，才能修改
	 * */
	@ResponseBody
	@RequestMapping("/deleteTransports")
	public ReturnVO deleteTransports(
			@RequestParam(value = "tableSelectedIds",required = false) String tableSelectedIds
	){

		User user = getLoginUser();
		try {

			if(tableSelectedIds!=null){
				String[] ids = tableSelectedIds.split(",");

				//验证 需要删除的ID对应的数据 是不是 已经 结转
				List<String> yearList =
						transportService.listYearByIds(ids);
				String carryMsg =
						rptService.checkDataCarry(yearList);
				if(!"".equals(carryMsg)){
					return failForService("400", ResponseInfoEnum.TRANSPORT_UPLOAD_FAILED,carryMsg);
				}

				transportService.deleteTransports(ids);
			}


		}catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("删除 错误:",e);
			return failForService("400", ResponseInfoEnum.TRANSPORT_DELETE_FAILED,e.getMessage());
		}
		return succForService(ResponseInfoEnum.TRANSPORT_DELETE_SUCCESS, null);

	}

	/**
	 * 新增 / 修改 保存数据
	 * */
	@ResponseBody
	@RequestMapping("/saveTransports")
	public ReturnVO saveTransports(
			Transport transport
	){

		User user = getLoginUser();
		try {
			Map<String,Object> conMap = new HashMap<String,Object>();
			conMap.put("transport", transport);
			conMap.put("user", user);


			//验证 是不是已经结转的数据
			List<String> yearList = new ArrayList<>();
			if(transport.getId()==null||
					"".equals(transport.getId())){
				//如果新增
				if(DateUtil.checkDateFormat(
						transport.getTransportDate(), "yyyy-MM-dd")){
					yearList.add(transport.getTransportDate().split("-")[0]);

				}
			}else{
				//如果是修改数据，需要查询修改的数据是不是  结转
				String[] ids = {transport.getId()};
				yearList =
						transportService.listYearByIds(ids);
				//判断修改后 数据是不是 结转
				if(DateUtil.checkDateFormat(
						transport.getTransportDate(), "yyyy-MM-dd")){
					if(!yearList.contains(transport.getTransportDate().split("-")[0]))
						yearList.add(transport.getTransportDate().split("-")[0]);
				}
			}
			String carryMsg =
					rptService.checkDataCarry(yearList);
			if(!"".equals(carryMsg)){
				return failForService("400", ResponseInfoEnum.TRANSPORT_SAVE_FAILED,carryMsg);
			}

			//添加验证
			String msg = checkData(transport,"1");
			if(!"".equals(msg)){
				return failForService("400", ResponseInfoEnum.TRANSPORT_SAVE_FAILED,msg);
			}

			transportService.saveTransports(transport,user);




		}catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("运输费 保存 错误:",e);
			return failForService("400", ResponseInfoEnum.TRANSPORT_SAVE_FAILED,e.getMessage());
		}
		return succForService(ResponseInfoEnum.TRANSPORT_SAVE_SUCCESS, null);

	}
	/**
	 * 添加验证
	 * @param transport 业务数据
	 * @param isCheckRepeat  是不是 需要验证重复数据  1：表示需要  其他表示不需要
	 *
	 * 如果 isCheckRepeat 是  1，表示 是 修改的数据，就不需要验证 是不是 重复
	 *
	 * */

	private String checkData(Transport transport,String isCheckRepeat) {
		// TODO Auto-generated method stub

		StringBuffer msg = new StringBuffer();
		msg.append("");

		//客户名称 不能为空
		if("".equals(transport.getCustomerName())){
			msg.append("【客户名称】不能为空! ");
		}else{
			//判断 客户名称有么有存在
			Map<String,Object> conMap = new HashMap<String,Object>();
			conMap.put("customerName",transport.getCustomerName());
			List<Customer> customerList =
					customerService.listCustomerByName(conMap);
			if(customerList==null ||
					customerList.size()==0){
				msg.append("【客户名称】："+transport.getCustomerName()+" 不存在，请先维护客户信息! ");
			}
		}


		//车主 不能为空
		if("".equals(transport.getCarOwner())){
			msg.append("【车主】不能为空! ");
		}else{
			//判断 客户名称有么有存在
			Map<String,Object> conMap = new HashMap<String,Object>();
			conMap.put("customerName",transport.getCarOwner());
			List<Customer> customerList =
					customerService.listCustomerByName(conMap);
			if(customerList==null ||
					customerList.size()==0){
				msg.append("【车主】："+transport.getCarOwner()+" 不存在，请先维护客户信息! ");
			}
		}

		//判断 日期
		if("".equals(transport.getTransportDate())){
			msg.append("【日期】不能为空! ");
		}

		//判断 车牌号
		if("".equals(transport.getCarNum())){
			msg.append("【车牌号】不能为空! ");
		}

		//判断 重量
		if("".equals(transport.getWeight())){
			//空的时候默认为0
			transport.setWeight("0");
		}else{
			if(!NumberUtil.isNumber(transport.getWeight())){
				msg.append("【重量】只能为 数字! ");
			}
		}

		//判断 单价
		if("".equals(transport.getUnitPrice())){
			//空的时候默认为0
			transport.setUnitPrice("0");
		}else{
			if(!NumberUtil.isNumber(transport.getUnitPrice())){
				msg.append("【单价】只能为 数字! ");
			}
		}

		//判断 金额
		if("".equals(transport.getAmount())){
			//空的时候默认为0
			transport.setAmount("0");
		}else{
			if(!NumberUtil.isNumber(transport.getAmount())){
				msg.append("【金额】只能为 数字! ");
			}
		}


		//判断 客户单价
		if("".equals(transport.getCustomerUnitPrice())){
			//空的时候默认为0
			transport.setCustomerUnitPrice("0");
		}else{
			if(!NumberUtil.isNumber(transport.getCustomerUnitPrice())){
				msg.append("【客户单价】只能为 数字! ");
			}
		}

		//判断 应收金额
		if("".equals(transport.getReceiveAmount())){
			//空的时候默认为0
			transport.setReceiveAmount("0");
		}else{
			if(!NumberUtil.isNumber(transport.getReceiveAmount())){
				msg.append("【应收金额】只能为 数字! ");
			}
		}

		//存在重复 验证
		if("1".equals(isCheckRepeat)){
			//判断 数据是不是已经存在
			//根据 【日期】【客户名称】【车牌】【重量】判断
			boolean flag =
					transportService.isTransportExist(transport);
			if(flag){
				msg.append("相同  记录已经存在! ");
			}
		}


		return msg.toString();
	}


}
